package com.dlry.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dlry.entity.DlLoginuser;
import com.dlry.entity.DlTravelRequest;
import com.dlry.serviceImpl.TravelService;
import com.dlry.serviceImpl.UserService;
import com.dlry.web.valid.TravelForm;

@Controller
@RequestMapping("/{roler}")
public class TravelController extends BaseController {
	@Autowired
	private TravelService travelService;
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/newtravel")
	public String newTravel(Model model, @PathVariable("roler") String roler) {
		model.addAttribute("travelForm", new TravelForm());
		model.addAttribute("roler", roler);
		return "newtravel";
	}

	@RequestMapping(value = "/savetravel")
	public String addTravel(@Valid TravelForm travelForm, BindingResult result, HttpServletResponse response,
			@PathVariable("roler") String roler, Model model) throws ParseException, IOException {

		if (result.hasErrors()) {
			model.addAttribute("roler", roler);
			return "newtravel";
		}
		DlTravelRequest travel = travelForm.toDlTravelRequest();
		DlLoginuser user = userService.findByName(getPrincipal());
		travel.setUser(user);
		travel.setName(user.getRealName());
		Date now = new Date();
		travel.setCreateDate(new Timestamp(now.getTime()));
		travelService.save(travel);
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		writer.println("提交成功，请关闭本页。");
		return null;
	}

	@RequestMapping(value = "/deletetravel")
	public String deleteTravel(Long tId, @PathVariable("roler") String roler) {
		travelService.delete(tId);
		return "redirect:/" + roler + "/travel";
	}
}
